package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断密码是否为空，空的话游客登录，没空的话验证
        if (StringUtils.isNotBlank(dto.getPassword())&& StringUtils.isNotBlank(dto.getPhone())){
//获取数据库里面的密码
            LambdaQueryWrapper<ApUser> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<ApUser> eq = objectLambdaQueryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(eq);
            if (one==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
             String password = dto.getPassword();//前端传过来的
             String phone = one.getPassword();//数据查出来的
             boolean checkpw = BCrypt.checkpw(password, phone);//比克乳癌特加密方式，对比
             if (!checkpw){
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
              }
              String token = AppJwtUtil.getToken(one.getId().longValue());
              Map map = new HashMap<>();
              map.put("token",token);
              map.put("user",one);
              return ResponseResult.okResult(map);

            }else {
            String token = AppJwtUtil.getToken(0L);
            Map map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
        }
    }

